package com.wenkew.common;

import java.text.MessageFormat;
import java.util.List;

import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.wenkew.model.AccessPermissions;
import com.wenkew.service.AccessPermissionsService;

public class ChainDefinitionSectionMetaSource implements FactoryBean<Section>{
	
	@Autowired
	private AccessPermissionsService accessPermissionsService;
	
	private String filterChainDefinitions;
	
	/**
	 * 默认premission字符串
	 */
	public static final String PREMISSION_STRING = "authc, perms[{0}]";

	@Override
	public Section getObject() throws Exception {
		
		Ini ini = new Ini();
		// 加载默认的url
		ini.load(filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);

		// 添加所有权限
		List<AccessPermissions> accessPermissionsList = accessPermissionsService.getAllAccessPermissions();

		for (AccessPermissions _accessPermissions : accessPermissionsList) {
			section.put("/" + _accessPermissions.getUrl(), MessageFormat.format(PREMISSION_STRING, _accessPermissions.getUrl()));
		}
		// 最后添加其他URL过滤，此处为anon，否则css、js等被拦截
		section.put("/**", "authc, roles[admin]");
		return section;
	}

	@Override
	public Class<?> getObjectType() {
		return this.getClass();
	}

	@Override
	public boolean isSingleton() {
		return false;
	}
	
	
	
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
	}
	
	final Logger logger = LoggerFactory.getLogger(ChainDefinitionSectionMetaSource.class);
	
}
